<template>
  <div>
    <el-card shadow="never" class="detail-card">
      <div slot="header" class="clearfix">
        <span>订单详情</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>

      <div v-loading="loading">
        <div v-if="order" class="order-content">
          <!-- 订单状态流程图 -->
          <div class="status-flow">
            <el-steps :active="statusStep" finish-status="success" align-center>
              <el-step title="待付款"></el-step>
              <el-step title="待发货"></el-step>
              <el-step title="已发货"></el-step>
              <el-step title="已完成"></el-step>
            </el-steps>
          </div>

          <!-- 订单基本信息 -->
          <div class="info-section">
            <h3>基本信息</h3>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">订单号：</span>
                  <span>{{ order.order_no }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">用户：</span>
                  <span>{{ order.user ? order.user.nickName : '-' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">订单状态：</span>
                  <span>
                    <el-tag v-if="order.status === 0" type="info">待付款</el-tag>
                    <el-tag v-else-if="order.status === 1" type="warning">待发货</el-tag>
                    <el-tag v-else-if="order.status === 2" type="primary">已发货</el-tag>
                    <el-tag v-else-if="order.status === 3" type="success">已完成</el-tag>
                    <el-tag v-else-if="order.status === 4" type="danger">已取消</el-tag>
                  </span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">支付方式：</span>
                  <span>
                    <el-tag v-if="order.payment_type === 0" type="primary">在线支付</el-tag>
                    <el-tag v-else-if="order.payment_type === 1" type="success">积分支付</el-tag>
                    <el-tag v-else-if="order.payment_type === 2" type="warning">混合支付</el-tag>
                  </span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">配送方式：</span>
                  <span>
                    <el-tag v-if="order.shipping_type === 0" type="primary">同城配送</el-tag>
                    <el-tag v-else-if="order.shipping_type === 1" type="success">快递</el-tag>
                  </span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">创建时间：</span>
                  <span>{{ order.create_time | dateFormat }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">总金额：</span>
                  <span>¥{{ order.total_amount }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">积分：</span>
                  <span>{{ order.total_points || 0 }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">运费：</span>
                  <span>¥{{ order.shipping_fee || 0 }}</span>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 收货信息 -->
          <div class="info-section">
            <h3>收货信息</h3>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">收货人：</span>
                  <span>{{ order.recipient_name }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">联系电话：</span>
                  <span>{{ order.recipient_phone }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">收货地址：</span>
                  <span>{{ order.recipient_address }}</span>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 物流信息 -->
          <div v-if="order.status >= 2" class="info-section">
            <h3>物流信息</h3>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">物流公司：</span>
                  <span>{{ order.shipping_company }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">物流单号：</span>
                  <span>{{ order.tracking_number }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">发货时间：</span>
                  <span>{{ order.shipping_time | dateFormat }}</span>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 支付信息 -->
          <div v-if="order.payment_type === 0 && order.status > 0" class="info-section">
            <wx-payment-info 
              :payment="order" 
              :show-actions="true"
              @refund="refundOrder"
              @query-payment="queryWxPayment"
            />
          </div>

          <!-- 退款记录 -->
          <div v-if="refundRecords.length > 0" class="info-section">
            <refund-records-list 
              :records="refundRecords"
              :loading="refundLoading"
              :show-actions="true"
              @query-status="queryRefundStatus"
            />
          </div>

          <!-- 商品信息 -->
          <div class="info-section">
            <h3>商品信息</h3>
            <el-table
              :data="order.details || []"
              border
              style="width: 100%"
            >
              <el-table-column align="center" label="商品图片" width="100">
                <template slot-scope="scope">
                  <el-image
                    v-if="scope.row.product_image"
                    style="width: 60px; height: 60px"
                    :src="scope.row.product_image"
                    :preview-src-list="[scope.row.product_image]"
                  ></el-image>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="product_name" label="商品名称" />
              <el-table-column label="价格" width="100">
                <template slot-scope="scope">
                  ¥{{ scope.row.price }}
                </template>
              </el-table-column>
              <el-table-column label="积分" width="100">
                <template slot-scope="scope">
                  {{ scope.row.points_price || 0 }}
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="80" />
              <el-table-column label="小计" width="120">
                <template slot-scope="scope">
                  ¥{{ scope.row.subtotal }}
                  <span v-if="scope.row.subtotal_points">
                    + {{ scope.row.subtotal_points }}积分
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 备注信息 -->
          <div v-if="order.remark" class="info-section">
            <h3>备注</h3>
            <p>{{ order.remark }}</p>
          </div>

          <!-- 操作按钮 -->
          <div class="action-section">
            <el-button 
              v-if="order.status === 1" 
              type="primary" 
              @click="shipOrder"
            >
              发货
            </el-button>
            <el-button 
              v-if="order.status === 2" 
              type="success" 
              @click="completeOrder"
            >
              完成订单
            </el-button>
            <el-button 
              v-if="order.status === 0" 
              type="danger" 
              @click="cancelOrder"
            >
              取消订单
            </el-button>
            <el-button 
              v-if="order.status === 1 && order.payment_type === 0 && order.wx_pay_status === 'paid'" 
              type="warning" 
              @click="refundOrder"
            >
              申请退款
            </el-button>
            <el-button 
              v-if="order.payment_type === 0 && order.wx_pay_status === 'paid'" 
              type="info" 
              @click="queryWxPayment"
            >
              查询支付状态
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 发货弹窗 -->
    <el-dialog
      title="订单发货"
      :visible.sync="shipVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="shipForm" :rules="shipRules" ref="shipFormRef" label-width="100px">
        <el-form-item label="物流公司" prop="shipping_company">
          <el-input v-model="shipForm.shipping_company" placeholder="请输入物流公司"></el-input>
        </el-form-item>
        <el-form-item label="物流单号" prop="tracking_number">
          <el-input v-model="shipForm.tracking_number" placeholder="请输入物流单号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipVisible = false">取 消</el-button>
        <el-button type="primary" :loading="shipLoading" @click="submitShip">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 取消订单弹窗 -->
    <el-dialog
      title="取消订单"
      :visible.sync="cancelVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="cancelForm" :rules="cancelRules" ref="cancelFormRef" label-width="100px">
        <el-form-item label="取消原因" prop="remark">
          <el-input 
            type="textarea" 
            v-model="cancelForm.remark" 
            placeholder="请输入取消原因"
            rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelVisible = false">取 消</el-button>
        <el-button type="primary" :loading="cancelLoading" @click="submitCancel">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 退款弹窗 -->
    <el-dialog
      title="申请退款"
      :visible.sync="refundDialogVisible"
      width="40%"
    >
      <el-form :model="refundForm" :rules="refundRules" ref="refundForm" label-width="100px">
        <el-form-item label="退款金额" prop="refund_amount">
          <el-input-number 
            v-model="refundForm.refund_amount" 
            :min="0.01" 
            :max="order ? order.total_amount : 0" 
            :precision="2" 
            :step="0.01"
          ></el-input-number>
          <span class="amount-tip">最大可退金额: ¥{{ order ? order.total_amount : 0 }}</span>
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input type="textarea" v-model="refundForm.reason" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRefund">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { http } from "@/api";
import WxPaymentInfo from "@/components/WxPaymentInfo";
import RefundRecordsList from "@/components/RefundRecordsList";
import { formatDate } from "@/utils";

export default {
  name: "OfficeOrderDetail",
  components: {
    WxPaymentInfo,
    RefundRecordsList
  },
  filters: {
    dateFormat(val) {
      if (!val) return "-";
      return formatDate(val);
    }
  },
  computed: {
    orderId() {
      return this.$route.params.id;
    },
    statusStep() {
      if (!this.order) return 0;
      if (this.order.status === 4) return 0; // 已取消
      return this.order.status + 1; // 0->1, 1->2, 2->3, 3->4
    }
  },
  data() {
    return {
      loading: false,
      order: null,
      refundRecords: [],
      refundLoading: false,
      shipVisible: false,
      shipLoading: false,
      cancelVisible: false,
      cancelLoading: false,
      refundDialogVisible: false,
      shipForm: {
        id: '',
        shipping_company: '',
        tracking_number: ''
      },
      cancelForm: {
        id: '',
        remark: ''
      },
      refundForm: {
        refund_amount: 0,
        reason: ""
      },
      shipRules: {
        shipping_company: [{ required: true, message: '请输入物流公司', trigger: 'blur' }],
        tracking_number: [{ required: true, message: '请输入物流单号', trigger: 'blur' }]
      },
      cancelRules: {
        remark: [{ required: true, message: '请输入取消原因', trigger: 'blur' }]
      },
      refundRules: {
        refund_amount: [
          { required: true, message: "请输入退款金额", trigger: "blur" }
        ],
        reason: [
          { required: true, message: "请输入退款原因", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getOrderDetail();
  },
  methods: {
    async getOrderDetail() {
      this.loading = true;
      try {
        const res = await http.officeOrder.read(this.orderId);
        this.order = res.data;
        // 获取退款记录
        this.getRefundRecords();
      } catch (error) {
        this.$message.error("获取订单详情失败");
      } finally {
        this.loading = false;
      }
    },
    async getRefundRecords() {
      this.refundLoading = true;
      try {
        const res = await http.officeOrderRefund.listByOrder(this.orderId);
        this.refundRecords = res.data || [];
      } catch (error) {
        console.error("获取退款记录失败", error);
      } finally {
        this.refundLoading = false;
      }
    },
    goBack() {
      this.$router.push('/officeShop/order');
    },
    shipOrder() {
      this.shipVisible = true;
      this.shipForm = {
        id: this.order.id,
        shipping_company: '',
        tracking_number: ''
      };
    },
    submitShip() {
      this.$refs.shipFormRef.validate(valid => {
        if (valid) {
          this.shipLoading = true;
          http.officeOrder.ship(this.shipForm).then(res => {
            this.$message.success('发货成功');
            this.shipVisible = false;
            this.getOrderDetail();
          }).finally(() => {
            this.shipLoading = false;
          });
        }
      });
    },
    completeOrder() {
      this.$confirm('确认将该订单标记为已完成?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.officeOrder.complete({ id: this.order.id }).then(res => {
          this.$message.success('操作成功');
          this.getOrderDetail();
        });
      });
    },
    cancelOrder() {
      this.cancelVisible = true;
      this.cancelForm = {
        id: this.order.id,
        remark: ''
      };
    },
    submitCancel() {
      this.$refs.cancelFormRef.validate(valid => {
        if (valid) {
          this.cancelLoading = true;
          http.officeOrder.cancel(this.cancelForm).then(res => {
            this.$message.success('取消成功');
            this.cancelVisible = false;
            this.getOrderDetail();
          }).finally(() => {
            this.cancelLoading = false;
          });
        }
      });
    },
    refundOrder() {
      this.refundForm.refund_amount = this.order.total_amount;
      this.refundForm.reason = "";
      this.refundDialogVisible = true;
    },
    async submitRefund() {
      this.$refs.refundForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await http.officeOrder.refundOrder({
              id: this.orderId,
              refund_amount: this.refundForm.refund_amount,
              reason: this.refundForm.reason
            });
            if (res.code === 0) {
              this.$message.success("退款申请提交成功");
              this.refundDialogVisible = false;
              this.getOrderDetail();
            } else {
              this.$message.error(res.message || "退款申请提交失败");
            }
          } catch (error) {
            this.$message.error("退款申请提交失败");
          }
        }
      });
    },
    async queryRefundStatus(refundId) {
      try {
        const res = await http.officeOrder.queryRefund(refundId);
        if (res.code === 0) {
          this.$message.success("查询成功");
          this.getRefundRecords();
        } else {
          this.$message.error(res.message || "查询退款状态失败");
        }
      } catch (error) {
        this.$message.error("查询退款状态失败");
      }
    },
    async queryWxPayment() {
      try {
        const res = await http.officeOrder.queryWxPayment(this.orderId);
        if (res.code === 0) {
          this.$message.success("查询成功");
          this.getOrderDetail();
        } else {
          this.$message.error(res.message || "查询支付状态失败");
        }
      } catch (error) {
        this.$message.error("查询支付状态失败");
      }
    }
  }
};
</script>

<style scoped>
.detail-card {
  margin-bottom: 20px;
}
.order-content {
  padding: 10px;
}
.status-flow {
  margin-bottom: 30px;
}
.info-section {
  margin-bottom: 30px;
}
.info-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
}
.info-item {
  margin-bottom: 10px;
}
.info-item .label {
  color: #606266;
  margin-right: 5px;
}
.action-section {
  margin-top: 30px;
  text-align: center;
}
.amount-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}
</style>
